let store
const storeTool = {
    init() {
        store = localforage.createInstance({ name: 'WaterMesh' })
        this.setConfig().then(() => {

        })
    },
    async setConfig() {
        await localforage.setDriver(localforage.INDEXEDDB)
        await this.getUseSize()
    },
    ruleList: new Set(),
    judgeUrl(url) {
        let has = !1;
        [...this.ruleList].forEach((item) => {
            has = url.indexOf(item) > -1 || item === '*'
        })

        return has
    },
    getItem: async(item) => await store.getItem(item),
    async setItem(key, value) {
        return await store.setItem(key, value)
    },
    async keys() {
        const keys = await store.keys()
        console.log(
            `%c浏览器 IndexDB 已缓存 ${keys.length} 个资源。`,
            'color:green'
        )
        return keys
    },
    async clear() {
        await store.clear()
    },
    async getUseSize() {
        if (void 0 === navigator?.storage?.estimate) {
            return void console.warn(
                '当前环境不支持 navigator.storage.estimate() 方法，原因可能是浏览器不支持或者页面不是通过 HTTPS 协议访问的。'
            )
        }
        const useInfo = await navigator?.storage?.estimate()
        if (useInfo) {
            const quota = (useInfo.usage / useInfo.quota) * 100
            let usage = useInfo.usage / 1024 / 1024
            usage =
                usage > 1024
                    ? (usage / 1024).toFixed(2) + ' GB'
                    : usage.toFixed(2) + ' MB'
            const maxCon = quota.toFixed(2)
            const gb = ((useInfo.quota - useInfo.usage) / 1024 / 1024 / 1024).toFixed(
                2
            )
            console.log(
                `%c当前站点的 IndexDB 已使用 ${usage}，占最大可用容量 ${maxCon} % 。最多可以再写入 ${gb} GB。`,
                'color:green'
            )
        }
        return useInfo
    }
}

export default storeTool
